//
//  CCRegisterViewController.m
//  02-用户登陆
//
//  Created by brother on 15/9/8.
//  Copyright (c) 2015年 CC. All rights reserved.
//

#import "CCRegisterViewController.h"

@interface CCRegisterViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *userPwd;
//确认密码
@property (weak, nonatomic) IBOutlet UITextField *userPwdRecur;

@end

@implementation CCRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (IBAction)registerClick:(UIButton *)sender {
    if (![self.userName.text isEqualToString:@""]&&![self.userPwd.text isEqualToString:@""]) {
        NSString *urlStr=[NSString stringWithFormat:@"http://localhost:8888/test/register.php?username=%@&password=%@",self.userName.text,self.userPwd];
        NSURL *url=[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
        
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSString *statusCode=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            
            if ([statusCode intValue]==0) {
                [self showAlertView:@"注册成功" Exit:YES];
            }
            else {
               [self showAlertView:@"注册失败" Exit:NO];
            }
        }];
    }
    else {
      [self showAlertView:@"信息填写不完整" Exit:NO];
    }
}

- (void)showAlertView:(NSString *)msg Exit:(BOOL)flag{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
       UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"提醒" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        
        [alertView show];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alertView dismissWithClickedButtonIndex:0 animated:YES];
            if(flag){
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        });
    }];
}
- (IBAction)back:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
